package com.sketch.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.sketch.commom.Result;
import com.sketch.commom.config.properties.WechatProperties;
import com.sketch.service.PayServer;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.h5.H5Service;
import com.wechat.pay.java.service.payments.h5.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PayServerImpl implements PayServer {

    @Autowired
    private AlipayClient alipayClient;

    @Value("${ali.notifyUrl}")
    private String notifyUrl;

    @Autowired
    private WechatProperties wechatProperties;
    /**
     * 文档地址 https://opendocs.alipay.com/open/cd12c885_alipay.trade.app.pay?scene=20&pathHash=ab686e33
     * @throws AlipayApiException
     */
    public Result aliPay(String billNo,String title,String amount) {
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        request.setNotifyUrl(notifyUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", billNo);
        bizContent.put("total_amount", amount);
        bizContent.put("subject", title);
        bizContent.put("product_code", "QUICK_MSECURITY_PAY");
        //bizContent.put("time_expire", "2022-08-01 22:00:00");

        //// 商品明细信息，按需传入
        //JSONArray goodsDetail = new JSONArray();
        //JSONObject goods1 = new JSONObject();
        //goods1.put("goods_id", "goodsNo1");
        //goods1.put("goods_name", "子商品1");
        //goods1.put("quantity", 1);
        //goods1.put("price", 0.01);
        //goodsDetail.add(goods1);
        //bizContent.put("goods_detail", goodsDetail);

        //// 扩展信息，按需传入
        //JSONObject extendParams = new JSONObject();
        //extendParams.put("sys_service_provider_id", "2088511833207846");
        //bizContent.put("extend_params", extendParams);
        request.setBizContent(bizContent.toString());
        AlipayTradeAppPayResponse response = null;
        try {
            response = alipayClient.sdkExecute(request);
            String orderStr = response.getBody();
            if (response.isSuccess()) {
                return Result.success();
            } else {
                log.error("支付失败",orderStr);
                return Result.error("支付失败");
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Result weChatPay(String billNo, String title, String total) {
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(wechatProperties.getMerchantId())
                        .privateKeyFromPath(this.getClass().getClassLoader().getResource(wechatProperties.getPrivateKeyPath()).getPath())
                        .merchantSerialNumber(wechatProperties.getMerchantSerialNumber())
                        .apiV3Key(wechatProperties.getApiV3Key())
                        .build();
        // 构建service
        H5Service builder = new H5Service.Builder()
                .config(config).build();
        PrepayRequest request =new PrepayRequest();

        Amount amount = new Amount();
        amount.setTotal((int) (Double.parseDouble(total)*100));
        request.setAmount(amount);
        request.setAppid(wechatProperties.getAppid());
        SceneInfo sceneInfo=new SceneInfo();
        sceneInfo.setPayerClientIp("192.142.121.12");
        //sceneInfo.setDeviceId();
        //sceneInfo.setStoreInfo();
        H5Info h5Info = new H5Info();
        h5Info.setType("h5");
        h5Info.setAppName("社区");
        sceneInfo.setH5Info(h5Info);
        request.setSceneInfo(sceneInfo);
        request.setMchid(wechatProperties.getMerchantId());
        request.setDescription(title);
        request.setNotifyUrl("https://localhost:8080/notify_url/callBack");
        request.setOutTradeNo(billNo);
        PrepayResponse prepay = null;
        try {
            prepay = builder.prepay(request);
        } catch (Exception e) {
            log.error("支付错误",e);
            prepay = new PrepayResponse();
            prepay.setH5Url("https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx2016121516420242444321ca0631331346&package=1405458241");
            //throw new RuntimeException(e);
        }
        return  Result.success(prepay.getH5Url());
    }
}
